package model

import (
	"common/helper"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strconv"
	"time"
)

type UrlParam struct {
	Uid        int    `json:"uid"`
	OperatorId string `json:"operator_id"` // 渠道id
	BusinessId string `json:"business_id"` // 业务员id
	StartTime  string `json:"start_time"`  // 查询开始时间
	EndTime    string `json:"end_time"`    // 查询结束时间
	Page       int    `json:"page"`
	PageSize   int    `json:"page_size"`
	OderBY     string `json:"order_by"`
	OderType   string `json:"order_type"`
	UserId     string `json:"user_id"`

	Status  string `json:"status"`
	IssueId string `json:"issue_id"`
	PrizeId string `json:"prize_id"`
}

type UrlConfig struct {
	Id        int    `db:"id" json:"id"`
	Url       string `db:"url" json:"url"`
	Status    int    `db:"status" json:"status"`
	CreatedAt int64  `db:"created_at" json:"created_at"`
}

type UrlConfigRetData struct {
	T int         `cbor:"t" json:"total"`
	D []UrlConfig `cbor:"d" json:"d"`
}

func GetUrlConfig(param UrlParam, ctx *fasthttp.RequestCtx) (UrlConfigRetData, error) {
	data := UrlConfigRetData{}
	table := "tbl_url_list"
	where := "1=1"
	join := ""
	oderBy := "a.id"
	oderType := "desc"

	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLoc(param.StartTime, loc)
		where += " and a.created_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLoc(param.EndTime, loc)
		where += " and a.created_at<='" + strconv.FormatInt(EndTime, 10) + "'"
	}
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}

	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateUrlConfig(param UrlConfig, isDelete int8) error {
	table := "tbl_url_list"
	query := ""
	record := param
	record.CreatedAt = time.Now().Unix()
	if param.Id > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.Id}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.Id}).ToSQL()
		}
	} else {

		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}
